package com.yy.sso.common.exceptions;

import com.yy.sso.common.constants.HttpStatusCodeConstant;
import com.yy.sso.common.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Slf4j
@RestControllerAdvice
public class HanderExceptions {

    /**
     * 处理自定义异常
     */
    @ExceptionHandler(BussinessException.class)
    public Result<Object> handleBussinessExceptionException(BussinessException e){
        log.info("自定义异常 " + e.getMessage(), e);
        return Result.error(HttpStatusCodeConstant.HTTP_CODE_ERROR,e.getMessage());
    }

    /**
     * 处理未知异常
     */
    @ExceptionHandler(Exception.class)
    public Result<Object> handleException(Exception e){
        log.error("未知异常[{}]",e.getMessage());
        return Result.error(HttpStatusCodeConstant.HTTP_CODE_ERROR,"未知异常，请联系管理员");
    }
    /**
     * 数据校验
     * @param e
     * @return
     */
    @ExceptionHandler(value = MethodArgumentNotValidException.class)
    public Result<Object> handlerMethodArgumentNotValidException(MethodArgumentNotValidException e){
        StringBuilder messages = new StringBuilder();
        for (ObjectError error : e.getBindingResult().getAllErrors()) {
            messages.append(",");
            if (error instanceof FieldError) {
                messages.append(((FieldError) error).getField()).append(":");
            }
            messages.append(error.getDefaultMessage() == null ? "":error.getDefaultMessage());
        }
        String msg = messages.toString().substring(1);
        log.error("methodArgumentNotValidException:{}", msg);
        return Result.error(500,msg);
    }
}
